package com.jfsnpm.controller;

import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfsnpm.authority.AuthorityCheck;
import com.jfsnpm.plugin.bjui.BjuiRender;
import com.jfsnpm.plugin.jfinal.captcha.pmCaptchaRender;

public class LoginController extends Controller {
	public void changepwd(){
		setAttr("userid", getSessionAttr("userid"));
		// 显示默认View
	}
	public void changepwdcheck(){
		/*if(getRequest().getContentType().startsWith("multipart")){
			getFile();
		}else{
			render(BjuiRender.code(802));
			return;
		}*/
		String userid = getPara("userid");
		String userpassword = getPara("userpassword");
		String newpassword = getPara("newpassword");
		new AuthorityCheck();
		if(!AuthorityCheck.changepsw(userid, userpassword, newpassword)){
			render(BjuiRender.error("修改密码失败！"));
		}else{
			render(BjuiRender.success("修改成功！"));
		}
	}
	
	// 以下登录操作无需拦截
	@Clear
	public void login(){
		// 注销操作
		new AuthorityCheck();
		AuthorityCheck.logout(this);
		
		String page = getPara("username");
		if(StringUtils.isBlank(page)){
			render("login.html");
			return;
		}else{
			setAttr("username", page);
			render("login_page.html");
			return;
		}
		
	}
	@Clear
	public void logincheck(){
		if(getRequest().getContentType().startsWith("multipart")){
			getFile();
		}
		// 验证登录
		String no = getPara("username");
		String password = getPara("userpassword");
		String captcha = getPara("captcha");
		String remember = getPara("remember");
		String t = getPara("t");
		if(StringUtils.isBlank(t)){render(BjuiRender.code(801));return;}
		if(!pmCaptchaRender.validate(this, captcha.toUpperCase(), t)){
			render(BjuiRender.error("验证码错误！"));
			return;
		}
		if(StringUtils.isBlank(no)||StringUtils.isBlank(password)){
			render(BjuiRender.code(801));
			return;
		}
		new AuthorityCheck();
		if(!AuthorityCheck.checkpsw("no",no,password,this,remember)){
			render(BjuiRender.error("账号或密码错误！"));
			return;
		}
		String tabid = getPara("reloadtab");
		if(StringUtils.isNotBlank(tabid)){
			render(BjuiRender.success("登录成功！").tabid(tabid));
			return;
		}
		render(BjuiRender.success("登录成功！"));
	}
	@Clear
	public void captcha(){
		// 验证码
		String t = getPara("t");
		if(StringUtils.isBlank(t)){renderNull();return;}
		render(new pmCaptchaRender(t));
	}
}
